#!/usr/bin/python
# -*- coding: utf-8 -*-
# @author  : ganuoxun
# @description : 贴源层api

from typing import List
from fastapi import APIRouter, Body
import datetime
from apps.database import bulk_write_ods, get_ods, update_ods, get_ods_result_by_id, get_ods_result, save_ods_result
from apps.models.BaseModel import UpdateOdsModel, OdsResultModel
from apps.models.QueryModel import QuerySchema
from apps.models.ResponseModel import error, success

router = APIRouter()


@router.post("/get")
async def get(query: QuerySchema = Body(...)):
    try:
        results = await get_ods(query.get_filter(),
                                query.get_projection(),
                                query.get_sort_by(),
                                query.skip,
                                query.limit)
        return success(results, "success")
    except Exception as e:
        print(e)
        return error(501, repr(e))


@router.post("/save")
async def save(update_list: List[UpdateOdsModel] = Body(...)):
    try:
        now = datetime.datetime.now()
        save_list = []
        id_set = set()
        for ods_date in update_list:
            if ods_date.lngid in id_set:
                return error(502, "存在重复的lngid：" + ods_date.lngid)

            id_set.add(ods_date.lngid)
            ods_date.upload_time = now
            ods_date.latest_date = now.strftime("%Y%m%d%H%M%S%f")
            save_list.append(ods_date.get_dict())
        return await bulk_write_ods(save_list)
    except Exception as e:
        print(e)
        return error(501, repr(e))


@router.post("/status_update")
async def update(ods_date: UpdateOdsModel = Body(...)):
    try:
        now = datetime.datetime.now()
        ods_date.upload_time = now
        ods_date.latest_date = now.strftime("%Y%m%d%H%M%S%f")

        update_dict = {
            'latest_date': ods_date.latest_date,
            'upload_time': ods_date.upload_time,
            'file_name': ods_date.file_name,
            'status': ods_date.status
        }

        if ods_date.error_info and len(ods_date.error_info) > 0:
            update_dict['error_info'] = ods_date.error_info
        return await update_ods({'_id': ods_date.lngid}, update_dict)
    except Exception as e:
        print(e)
        return error(501, repr(e))


@router.get("/result/get_by_id/{_id}")
async def get_result_by_id(_id: str):
    try:
        return await get_ods_result_by_id(_id)
    except Exception as e:
        print(e)
        return error(501, repr(e))


@router.post("/result/get")
async def get_result(query: QuerySchema = Body(...)):
    try:
        results = await get_ods_result(query.get_filter(),
                                       query.get_sort_by(),
                                       query.skip,
                                       query.limit)
        return success(results, "success")
    except Exception as e:
        print(e)
        return error(501, repr(e))


@router.post("/result/save")
async def save_result(ods_result: OdsResultModel = Body(...)):
    try:
        ods_result.latest_date = datetime.datetime.now().strftime("%Y%m%d%H%M%S%f")
        return await save_ods_result(ods_result.lngid,
                                     ods_result.lngid + '.json',
                                     ods_result.get_result(),
                                     ods_result.get_metadata())
    except Exception as e:
        print(e)
        return error(501, repr(e))
